package com.warmlight.voicepacket.ui.setting;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.base.BaseActivity;
import com.warmlight.voicepacket.data.UserCenterData;
import com.warmlight.voicepacket.data.VersionCheck;
import com.warmlight.voicepacket.data.eventbus.Login;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.http.ResponseData;
import com.warmlight.voicepacket.ui.user.FeedBackActivity;
import com.warmlight.voicepacket.ui.user.UserEditInformation;
import com.warmlight.voicepacket.utils.DownloadHelper;
import com.warmlight.voicepacket.utils.FileUtils;
import com.warmlight.voicepacket.utils.MobClickHelper;
import com.warmlight.voicepacket.utils.SPUtils;
import com.warmlight.voicepacket.utils.UIUtils;
import com.warmlight.voicepacket.web.WebViewActivity;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.rong.imkit.RongIM;
import okhttp3.Call;

public class SettingActivity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout rl_my_info;
    private TextView tv_nickname;
    private RelativeLayout rl_clear_cache;
    private TextView tv_cache;
    private RelativeLayout rl_feedback;
    private RelativeLayout rl_about_wanpi;
    private Button bt_logout;
    private TextView tv_vision_name;
    private RelativeLayout rl_secrit;
    private RelativeLayout rl_user_use_read;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        initView();
        initLinstener();
        initData();
    }

    private void initData() {
        setTitle("设置");
        setBack();
        if (SPUtils.isLogined()){
            rl_my_info.setVisibility(View.VISIBLE);
            bt_logout.setVisibility(View.VISIBLE);
            UserCenterData.AuthorBean loginUser = SPUtils.getLoginUser();
            tv_nickname.setText(loginUser.getNickname());
        }else{
            rl_my_info.setVisibility(View.GONE);
            bt_logout.setVisibility(View.GONE);
        }


//        File file = SettingActivity.this.getExternalCacheDir();
//        File glidecache = Glide.getPhotoCacheDir(SettingActivity.this);
//        long total = FileUtils.getFolderSize(file);
//        long cache = FileUtils.getFolderSize(glidecache);
//        long cachesize = cache + total;
//        String size = FileUtils.getFormatSize(cachesize);//格式转换
//        tv_cache.setText(size);
        tv_vision_name.setText(UIUtils.getPackageName());
    }

    private void initLinstener() {
        rl_my_info.setOnClickListener(this);
        rl_clear_cache.setOnClickListener(this);
        rl_feedback.setOnClickListener(this);
        rl_about_wanpi.setOnClickListener(this);
        bt_logout.setOnClickListener(this);
        rl_secrit.setOnClickListener(this);
        rl_user_use_read.setOnClickListener(this);
    }

    private void initView() {

        rl_my_info = (RelativeLayout) findViewById(R.id.rl_my_info);
        tv_nickname = (TextView) findViewById(R.id.tv_nickname);
        rl_clear_cache = (RelativeLayout) findViewById(R.id.rl_clear_cache);
        tv_cache = (TextView) findViewById(R.id.tv_cache);
        rl_feedback = (RelativeLayout) findViewById(R.id.rl_feedback);
        rl_about_wanpi = (RelativeLayout) findViewById(R.id.rl_about_wanpi);

        bt_logout = (Button) findViewById(R.id.bt_logout);
        tv_vision_name = (TextView) findViewById(R.id.tv_vision_name);

        rl_secrit = (RelativeLayout) findViewById(R.id.rl_secrit);
        rl_user_use_read = (RelativeLayout) findViewById(R.id.rl_user_use_read);
    }
    private ProgressDialog progressDialog;
    //android.R.style.Theme_Material_Light_Dialog_Alert
    private void showProgressDialog(String msg){
        if (progressDialog != null && progressDialog.isShowing()){
            return;
        }
        if (progressDialog == null){
            progressDialog = new ProgressDialog(this,android.R.style.Theme_Material_Light_Dialog_Alert);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.setMessage(msg);

        progressDialog.show();
    }

    private void hideProgressDialog(){
        if (progressDialog != null){
            if (progressDialog.isShowing()){
                progressDialog.dismiss();
            }
        }
    }
    private void clearCache(){
        File file = getContext().getExternalCacheDir();
        try {
            showProgressDialog("正在清理缓存");
            FileUtils.deleteFolderFile(file.getAbsolutePath(), false);
            Glide.get(SettingActivity.this).clearMemory();
            new Thread(new Runnable() {
                public void run() {
                    Glide.get(getContext()).clearDiskCache();
                }
            }).start();
            Glide.get(SettingActivity.this).clearMemory();
            Timer timer = new Timer();
            TimerTask tk = new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            File file = SettingActivity.this.getExternalCacheDir();
                            File glidecache = Glide.getPhotoCacheDir(SettingActivity.this);
                            long total = FileUtils.getFolderSize(file);
                            long cache = FileUtils.getFolderSize(glidecache);
                            long cachesize = cache + total;
                            String size = FileUtils.getFormatSize(cachesize);//格式转换
                            tv_cache.setText(size);
                            hideProgressDialog();
                        }
                    });
                }
            };
            timer.schedule(tk, 3000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rl_my_info:
                //埋点
                MobclickAgent.onEvent(getContext(), MobClickHelper.SETING_INFO);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
                ZhugeSDK.getInstance().track(getContext(), MobClickHelper.SETING_INFO);
                Intent intent2 = new Intent(getContext(), UserEditInformation.class);
                startActivity(intent2);
                break;
            case R.id.rl_clear_cache:
                showDialogClearCache();
                break;
            case R.id.rl_feedback:
                //埋点
                MobclickAgent.onEvent(getContext(), MobClickHelper.SETING_FEEDBACK);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
                ZhugeSDK.getInstance().track(getContext(), MobClickHelper.SETING_FEEDBACK);
                Intent intent = new Intent(getContext(), FeedBackActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_about_wanpi:
                //埋点
                MobclickAgent.onEvent(getContext(), MobClickHelper.SETING_VISION);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
                ZhugeSDK.getInstance().track(getContext(), MobClickHelper.SETING_VISION);
                checkVersion();
                break;

            case R.id.bt_logout://埋点
                MobclickAgent.onEvent(getContext(), MobClickHelper.SETING_LOGOUT);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
                ZhugeSDK.getInstance().track(getContext(), MobClickHelper.SETING_LOGOUT);
                showDialogLogout();
                break;

            case R.id.rl_secrit:
                WebViewActivity.loadUrl(getContext(),HttpConfig.USERPRIVACY,"隐私策略");
                break;
            case R.id.rl_user_use_read:
                WebViewActivity.loadUrl(getContext(),HttpConfig.USERCONDINTION,"用户使用条款");
                break;

        }
    }

    private void showDialogClearCache(){
        AlertDialog dialog = new AlertDialog.Builder(getContext())
                .setMessage("确定清除缓存图片和数据吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        clearCache();
                        dialog.dismiss();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }


    private void showDialogLogout() {
        AlertDialog dialog = new AlertDialog.Builder(getContext())
                .setMessage("确定退出当前账号？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //埋点
                        MobclickAgent.onEvent(getContext(), MobClickHelper.SETING_LOGOUT_YES);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
                        ZhugeSDK.getInstance().track(getContext(), MobClickHelper.SETING_LOGOUT_YES);
                        logoutWanPi();
                        dialog.dismiss();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //埋点
                        MobclickAgent.onEvent(getContext(), MobClickHelper.SETING_LOGOUT_NO);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
                        ZhugeSDK.getInstance().track(getContext(), MobClickHelper.SETING_LOGOUT_NO);
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }

    private void logoutWanPi(){
        String logout = HttpConfig.LOGOUT;
        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("auth_key",SPUtils.getLoginAuthKey());
        HttpClient.getInstance().postRxAndroidAES(logout,treeMap)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData responseData) {
                        if (TextUtils.equals("200",responseData.getCode())){
                            SPUtils.logout();
                            EventBus.getDefault().post(new Login(false));
                            RongIM.getInstance().disconnect();
                            RongIM.getInstance().logout();
                            finish();
                        }else{
                            showToast(responseData.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        showToast("网络错误，请稍后重试");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
    //监测版本
    private void checkVersion(){
        TreeMap<String, String> map = new TreeMap<>();
        map.put("version", UIUtils.getPackageName());
        map.put("app_id","1");

        HttpClient.post(HttpConfig.SERVER+ HttpConfig.VERSION, map, new com.warmlight.voicepacket.http.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("WLVP","获取服务器版本号失败");
            }

            @Override
            public void onResponse(Call call, final String response)   {
                try {
//                    final String s = response.body().string();
                    final VersionCheck data = new Gson().fromJson(response,VersionCheck.class);

                    (getContext()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.e("TAG","response="+response);
                            if(data.getData() != null){
                                if(data.getData().isIs_upgrade()){
                                    Log.e("Version","需要升级");

                                    showVersionDialog(data.getData());

                                }else{
                                    showToast("已是最新版本");
                                    Log.e("Version","不需要升级");
                                }
                            }else{
                                showToast("已是最新版本");
                            }
                        }
                    });
                }catch (Exception e){

                }
            }
        });
    }

    private void showVersionDialog(final VersionCheck.DataBean data){
        if (data.isIs_force()){
            downloadAPK(data.getDownload_url());
        }else{
            AlertDialog.Builder builder = new AlertDialog.Builder(this,android.R.style.Theme_Material_Light_Dialog_Alert).setTitle("版本更新")
                    .setMessage(data.getDesc())
                    .setNegativeButton(data.getConfirm_txt(), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            downloadAPK(data.getDownload_url());
                        }
                    }).setPositiveButton(data.getCancel_txt(), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            builder.create().show();
        }
    }

    private void downloadAPK(String download_url){
        showProgressDialog();
        DownloadHelper.getInstance().download(download_url, "voicepacket.apk", new DownloadHelper.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(final File file) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hideProgressDialog2();
                        anzhuang(file);
                    }
                });

            }

            @Override
            public void onDownloading(final int progress) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        setmProgressDialog(progress);
                    }
                });
            }

            @Override
            public void onDownloadFailed(Exception e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hideProgressDialog2();
                        showToast("下载失败，请稍后再试");
                    }
                });
            }
        });
    }

    private void anzhuang(File file){
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(getContext(), "com.warmlight.voicepacket.FileProvider", file);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        startActivity(intent);
        //强制更新就把应用关掉
//        android.os.Process.killProcess(android.os.Process.myPid());
    }

    private ProgressDialog mProgressDialog;

    private void showProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setTitle("下载更新");
        mProgressDialog.setMax(100);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setCanceledOnTouchOutside(false);
//        mProgressDialog.setProgressDrawable(this.getResources()
//                .getDrawable(R.drawable.seekbar_progress));
        mProgressDialog.show();
    }

    private void setmProgressDialog(int progress){
        if (mProgressDialog != null){
            mProgressDialog.setProgress(progress);
        }
    }

    private void hideProgressDialog2(){
        if (mProgressDialog != null){
            mProgressDialog.dismiss();
        }
    }


}
